package com.hxzy.controller;

import com.hxzy.common.R;
import com.hxzy.entity.User;
import com.hxzy.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/users")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    //登录
    @PostMapping("/login")
    public R<User> login(HttpServletRequest request, @RequestBody User user){
        User user1 = userService.selectByNameAndPassword(user);
        if (user1 != null){
            request.getSession().setAttribute("user",user1);
            return R.success(user1);
        }
        else {
            return R.error("没有此用户,请检查用户名和密码");
        }
    }

    //注册
    @PostMapping("/register")
    public R<String> register(@RequestBody User user){
    log.info("进入register()方法...");
    userService.addUser(user);
    return R.success("注册成功!");
    }

    //退出
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return R.success("退出成功!");
    }
}
